<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img class="preview" v-if="avatar" :src="avatar" alt="" />
      <img
        class="preview"
        v-else
        src="../../../assets/images/avatar.jpg"
        alt=""
      />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <!-- accept中要写一个MIMETYPE -->
        <input
          @change="fileHandler"
          accept="image/*"
          ref="file"
          type="file"
          style="display: none"
        />
        <el-button
          @click="$refs.file.click()"
          type="primary"
          icon="el-icon-plus"
        >
          选择图片
        </el-button>
        <el-button
          @click="updateAvatar"
          type="success"
          icon="el-icon-upload"
          :disabled="!avatar"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    // selectHandler () {
    //   this.$refs.file.click()
    // }
    fileHandler (e) {
      // console.log(e)
      if (e.target.files.length === 0) return
      const file = e.target.files
      // console.log(file[0])
      // 拿到的值不能直接渲染到img标签,img标签的src中只能写url或base64
      // 借助一个工具,将blob转为base64 FileReader
      const reader = new FileReader()
      //   console.log(reader)
      reader.readAsDataURL(file[0])
      // 读取文件是异步操作,所以要用事件来获取结果
      reader.onload = (e) => {
        // console.log(e.target.result)
        this.avatar = e.target.result
      }
    },
    async updateAvatar () {
      // 将用户选择的头像上传给服务器
      // get:获取数据,对应着后端的select
      // post:提交数据,用户后端添加一些数据insert into
      // delete:删除数据,对应着后端delete
      // put:整体更新,{id:1,username:'zs',nickname:'张'...}将整个用户信息都更新
      // patch: 局部更新,{avavtar:"xxx"}
      // console.log(this.avatar)
      const { data: res } = await this.$axios.patch('/my/update/avatar', {
        avatar: this.avatar
      })
      console.log(res)
      if (res.code !== 0) return /* this.$message.error(res.message) */
      // this.$message.success(res.message)
      this.$store.dispatch('getUserInfo', {
        user_pic: this.avatar
      })
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
  width: 350px;
  height: 360px;
}
</style>
